package com.liusand.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.liusand.common.ThreadLocalUtils;
import com.liusand.exception.CategoryException;
import com.liusand.mapper.CategoryMapper;
import com.liusand.pojo.Category;
import com.liusand.pojo.PageInfo;
import com.liusand.service.CategoryService;
import com.liusand.vo.CategoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :liusha
 * packageName :com.liusand.service.impl
 * fileName :CategoryServiceImpl
 * creationTime :2022/11/22 14:58
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public PageInfo<Category> page(Integer page, Integer pageSize) {
        Integer start = (page - 1) * pageSize;
        List<Category> pages = categoryMapper.page(start, pageSize);

        PageInfo<Category> pageInfo = new PageInfo<>();
        pageInfo.setCurrent(page);
        pageInfo.setSize(pageSize);
        pageInfo.setRecords(pages);
        pageInfo.setTotal(categoryMapper.countPage());
        return pageInfo;
    }

    @Override
    public List<Category> list(Integer type) {
        List<Category> categories = categoryMapper.list(type);
        return categories;
    }

    @Override
    public boolean saveCategory(Category category) {
        Category categoryInDb = categoryMapper.findByName(category.getName());
        if(categoryInDb != null){
            throw new CategoryException("'"+categoryInDb.getName()+"'已存在");
        }
        category.setId(IdUtil.getSnowflakeNextIdStr());
        String id = ThreadLocalUtils.getId();
        category.setCreateUser(id);
        category.setUpdateUser(id);
        return categoryMapper.saveCategory(category) > 0;
    }

    @Override
    public boolean deleteCategoryById(String id) {
        //todo 判断分类下是否有套餐/菜品
        return categoryMapper.deleteCategoryById(id) > 0;
    }

    @Override
    public boolean updateCategory(Category category){
        Category categoryInDb = categoryMapper.findByName(category.getName());
        if(categoryInDb != null && !categoryInDb.getId().equals(category.getId())){
            throw new CategoryException("'"+categoryInDb.getName()+"'已存在");
        }
        category.setUpdateTime(LocalDateTime.now());
        String id = ThreadLocalUtils.getId();
        category.setUpdateUser(id);
        return categoryMapper.updateCategory(category) > 0;
    }
}
